package io.github.jsp.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicLong;

public class ServerIdUtil {
    private static String serverId = null;
    private static String nodeId = null;
    private static String serverAddress = null;
    private static final AtomicLong counter = new AtomicLong(0);
    
    static {
        init();
    }
    
    private static void init() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            String hostname = localHost.getHostName();
            String ipAddress = localHost.getHostAddress();
            
            NetworkInterface network = NetworkInterface.getByInetAddress(localHost);
            byte[] mac = network.getHardwareAddress();
            StringBuilder macStr = new StringBuilder();
            if (mac != null) {
                for (int i = 0; i < mac.length; i++) {
                    macStr.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                }
            }
            
            serverId = hostname + "_" + ipAddress + "_" + macStr.toString();
            serverAddress = ipAddress + ":" + getServerPort();
            nodeId = hostname + "_" + ipAddress + "_" + System.currentTimeMillis();
            
        } catch (Exception e) {
            serverId = "server_" + System.currentTimeMillis() + "_" + Math.random();
            serverAddress = "unknown:8080";
            nodeId = "node_" + System.currentTimeMillis();
        }
    }
    
    public static String getServerId() {
        return serverId;
    }
    
    public static String getNodeId() {
        return nodeId;
    }
    
    public static String getServerAddress() {
        return serverAddress;
    }
    
    public static long generateId() {
        return System.currentTimeMillis() * 1000 + counter.incrementAndGet() % 1000;
    }
    
    private static String getServerPort() {
        try {
            String port = System.getProperty("server.port");
            if (port != null) {
                return port;
            }
            return "8080";
        } catch (Exception e) {
            return "8080";
        }
    }
}